package com.jxlc.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jxlc.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 *mybatis-plus字段自动填充
 */
@Component
@Slf4j
public class AutoFillHandler implements MetaObjectHandler {

    /**
     * 新增时填入值
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        /*
         * 3 种情况不填充
         * 1 值为null
         * 2 自动类型不匹配
         * 3 没有改字段
         */
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createBy", Long.class, userId);
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateBy", Long.class, userId);
        this.strictInsertFill(metaObject, "createDate", Date.class, new Date());

    }


    /**
     * 修改时填入值
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "updateBy", Long.class, userId);
        this.strictUpdateFill(metaObject, "updateDate", Date.class, new Date());

    }

    /**
     * 获取安全上下文里的用户对象
     */
    private Long getUserId() {
        try {
            return SecurityUtils.getUserId();
        }catch (Exception e){
            log.error("mybatis-plus数据填充发生异常：{}",e.getMessage());
            return 1L;
        }

    }
}
